#include "EPSGV/Application.h"

#ifdef _WIN32
	#include "Windows.h"
#endif

#include "GL/gl.h"
#include "GL/glut.h"

#include <stdio.h>

#include "EPSG/Scene.h"
#include "EPSG/Engine.h"

#include "EPSGLua/LuaFunctions.h"

EPSG::Scene* EPSGV::Application::s_root = NULL;

EPSGV::Application::Application( int argc, char* args[] )
{
	glutInit( &argc, args );
	glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGB );
	glutInitWindowSize( 800, 600 );
	glutCreateWindow( "E.P. Scene Graph Viewer" );
	glutDisplayFunc( &EPSGV::Application::redraw );
	glutKeyboardFunc( &EPSGV::Application::keyboard );
	glutMouseFunc( &EPSGV::Application::mouse );
	glutMotionFunc( &EPSGV::Application::motion );

	EPSG::Scene::getSignalSceneLoaded().connect( this, &EPSGV::Application::loadScene );
	//EPSGLua::LuaFunctions::getSignalUpdated().connect( this, &EPSGV::Application::updateView );
}

void EPSGV::Application::execute()
{
	if( s_root == NULL )
		printf( "No scene was created!\n" );
	else
		glutMainLoop();
}

void EPSGV::Application::loadScene( EPSG::Scene* root )
{
	s_root = root;
}

void EPSGV::Application::redraw()
{
	if( s_root == NULL )
		return;

	s_root->render();
	glutSwapBuffers();
}

void EPSGV::Application::keyboard( unsigned char key, int x, int y )
{
	if( EPSG::Engine::execute( key, x, y ) )
		redraw();
}

void EPSGV::Application::mouse( int button, int state, int x, int y )
{
	if( EPSG::Engine::execute( button, state, x, y ) )
		redraw();
}

void EPSGV::Application::motion( int x, int y )
{
	if( EPSG::Engine::execute( x, y ) )
		redraw();
}

void EPSGV::Application::updateView()
{
	redraw();
}